import { Button, Col, Form, Input, Row, Radio, message, Space } from 'antd'
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import './login.scss'
import React, { useState, useEffect } from 'react'
import { http } from '../utils'

let timeChange
const Register = () => {

  const [email, setEmail] = useState('')
  //注册请求
  const rigister = async ({ email, identity, password, username, verify }) => {
    const res = await http.post('/user_server/api/v1/pub/user/register', {  // eslint-disable-line no-unused-vars
      email, identity, password, username, verify
    })
  }
  //
  const onFinish = async (values) => {
    console.log('Success:', values)
    try {
      await rigister({
        email: values.email,
        identity: values.identity,
        password: values.password,
        username: values.username,
        verify: values.verify
      })
      message.success('注册成功')
    } catch (e) {
      message.error(e.response?.data?.message || '注册失败')
    }
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }

  //定时器
  const [time, setTime] = useState(60)
  const [btnboole, setBtnboole] = useState(false)
  const [btnText, setBtnText] = useState('获取验证码')

  useEffect(() => {
    clearInterval(timeChange)
    return () => clearInterval(timeChange)
  }, [])

  useEffect(() => {
    if (time > 0 && time < 60) {
      setBtnText(`${time}s后重发`)
    } else {
      clearInterval(timeChange)
      setBtnboole(false)
      setTime(60)
      setBtnText('获取验证码')
    }
  }, [time])

  //验证码
  const sending = async () => {
    try {
      console.log(email)
      await getcaptcha(email)
      timeChange = setInterval(() => setTime(t => --t), 1000)
      setBtnboole(true)

    } catch (e) {
      message.error(e.response?.data?.message || '获取验证码失败')
    }
  }
  //
  //
  const getcaptcha = async (email) => {
    const captcha = await http.post(`/user_server/api/v1/pub/notify/captcha/email${'?email='}${email}`)  // eslint-disable-line no-unused-vars
  }
  return (

    < div className="form-container sign-up-container" >
      <Form
        className='form-login'
        name="basic"
        id='register'
        labelAlign='left'
        validateTrigger={['onBlur', 'onChange']}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 14,
        }}
        initialValues={{
          remember: false,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          name="identity"
          label='身份'
          rules={[
            {
              required: true,
              message: '请选择用户身份',
            },
          ]}
        >
          <Radio.Group value={0}>
            <Radio value={0}>学生</Radio>
            <Radio value={1}>教师</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="username"
          label='账号'
          rules={[
            {
              required: true,
              message: '请输入用户名',
            },
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="Username"
            id="register_username"
          />
        </Form.Item>
        <Form.Item
          name="password"
          label='密码'
          rules={[
            {
              required: true,
              message: 'Please input your password!',
            },
          ]}
        >
          <Input.Password prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="Password"
            id="register_password"
          />
        </Form.Item>
        <Form.Item
          name="email"
          label='邮箱'
          rules={[
            {
              required: true,
              message: '请输入邮箱',
            },
            {
              pattern: /^[-a-z0-9~!$%^&*_=+}{'?]+(\.[-a-z0-9~!$%^&*_=+}{'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i,
              message: '请输入正确的邮箱',
              validateTrigger: 'onBlur'

            }
          ]}
        >
          <Input
            placeholder="请输入邮箱"
            id="email"
            onChange={(e) => setEmail(e.target.value)}
          />
        </Form.Item>
        <Form.Item
          name="verify"
          label='验证码'
          rules={[
            {
              required: true,
              message: '请输入邮箱验证码',
            }, {
              pattern: 6,
              message: '请输入正确的验证码',
              validateTrigger: 'onBlur'

            }
          ]}
        >
          <Space>
            <Col>
              <Input
                placeholder="请输入邮箱验证码"
                id="register_email"
              />
            </Col>
            <Col>
              <Button type='primary' disabled={btnboole} onClick={() => sending()} >{btnText}</Button>

            </Col>
          </Space>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit"  >
            注册
          </Button>
        </Form.Item>
      </Form>
    </div >
  )
}

export default Register